package com.spzx.channel.configure;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

@Configuration
public class ThreadPoolConfig {

    /**
     * cpu 计算型, 时间短的任务。线程数是CPU 2倍即可。
     *
     * i/o 吞吐型任务, 时间较长的任务。线程数一般设置和CPU核数相等即可。
     */
    @Bean
    public ThreadPoolExecutor threadPoolExecutor(){
        int processorsCount = Runtime.getRuntime().availableProcessors(); //获取cpu数量
        System.out.println("processorsCount = " + processorsCount); // processorsCount = 12
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
                processorsCount*2, //核心线程数量
                processorsCount*2, //最大线程数据量
                0, //空闲线程销毁等待时间。
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(200),
                Executors.defaultThreadFactory(),
                //new ThreadPoolExecutor.AbortPolicy()
                (runnable, threadPoolExecutor1 ) ->{ //RejectedExecutionHandler
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                    }
                    threadPoolExecutor1.submit(runnable); //达到了饱和策略，就睡觉后重新将任务交给线程池再次处理。
                }
        );
        threadPoolExecutor.prestartAllCoreThreads(); //创建线程池的同时，初始化核心线程数。
        return threadPoolExecutor;
    }
}
